import AntModal from '@/components/pt/dialog/AntModal'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import BizProduct from '@/views/biz/bizorder/modules/BizProduct'
import { auditPurchase, addBizPurchase, updateBizPurchase, delBizPurchaseDetail,delBizPurchase } from '@/api/biz/bizPurchase'
import { addBizPayable, updateBizPayable,delBizPayable } from '@/api/biz/bizPayable'
import { listBizWarehouseSpaceByWarehouseId } from '@/api/biz/bizWarehouseSpace'
import SelectUser from '@/components/pt/selectUser/SelectUser'
import SelectDept from '@/components/pt/selectDept/SelectDept'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import moment from 'moment';
import {randomUUID} from "@/utils/util"
import tableDragResizeMixin from '@/mixins/tableDragResizeMixin'
export default {
  name: 'CreateForm',
  props: {
    supplierOptions: {
      type: Array,
      required: true
    },
    warehouseIdOptions: {
      type: Array,
      required: true
    },
    payOptions: {
      type: Array,
      required: true
    },
  },
  mixins:[tableDragResizeMixin],
  components: {
    AntModal,
    SelectUser,
    SelectDept,
    BizProduct,
    AdvanceTable
  },
  data () {
    return {
      showProductModal:false,
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/upload",
      // 设置上传的请求头部
      headers: { Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN) },
      multiple:false,
      open: false,
      closeDialog: true,
      spinning: false,
      delayTime: 100,
      labelCol: { span: 14 },
      wrapperCol: { span: 14 },
      loading: false,
      disabled: false,
      total: 0,
      id: undefined,
      formTitle: '添加销售单',
      // 表单参数
      form: {},
      attachmentRefName: 'addUploaderFile', // 标志表单是否含有附件
      formId: '',
      spaceList:[],
      dataSource:[],
      disabledCreated:true,
      rules: {
        supplierCode: [{ required: true, message: '供应商不能为空', trigger: 'blur' }],

        warehouseId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }]

      },
      columns: [
        {
          title: '存货编码',
          dataIndex: 'productCode',
          align: 'center',
          width: '15%'
        },
        {
          title: '颜色',
          dataIndex: 'color',
          align: 'center',
          width: '5%'
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          align: 'center',
          width: '5%'
        },
        {
          title: '规格',
          dataIndex: 'spec',
          align: 'center',
          width: '10%'
        },
        {
          title: '型号',
          dataIndex: 'model',
          align: 'center',
          width: '10%'
        },
        {
          title: '仓位',
          dataIndex: 'spaceId',
          align: 'center',
          width: '10%',
          scopedSlots: {
            customRender: 'spaceIdSlot'
          },
        },
        {
          title: '数量',
          dataIndex: 'productNumber',
          align: 'center',
          scopedSlots: {
            customRender: 'productNumberSlot'
          },
          width: '8%'
        },
        {
          title: '单位',
          dataIndex: 'unit',
          align: 'center',
          scopedSlots: {
            customRender: 'unitSlot'
          },
          width: '8%'
        },
        {
          title: '单价',
          dataIndex: 'unitPrice',
          align: 'center',
          scopedSlots: {
            customRender: 'unitPriceSlot'
          },
          width: '8%'
        },
        {
          title: '金额',
          dataIndex: 'totalAmount',
          align: 'center',
          scopedSlots: {
            customRender: 'totalAmountSlot'
          },
          width: '8%'
        },
        {
          title: '毛利',
          dataIndex:'balance',
          align: 'center'
        },
        {
          title: '成本',
          dataIndex:'amount',
          align: 'center'
        },
        {
          title: '备注',
          dataIndex: 'remark',
          align: 'center',
          scopedSlots: {
            customRender: 'remarkSlot'
          },
          width: '10%'
        },
        {
          title: '操作',
          align: 'center',
          width: '20%',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      columns1: [
        {
          title: '付款账户',
          dataIndex: 'payAccount',
          align: 'center',
          width: '20%',
          scopedSlots: {
            customRender: 'payAccountSlot'
          }
        },
        {
          title: '付款金额',
          dataIndex: 'payAmount',
          align: 'center',
          scopedSlots: {
            customRender: 'payAmountSlot'
          }
        },
        {
          title: '付款时间',
          dataIndex: 'payDate',
          align: 'center',
          scopedSlots: {
            customRender: 'payDateSlot'
          }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          align: 'center',
          scopedSlots: {
            customRender: 'remarkSlot'
          }
        },
        {
          title: '操作',
          align: 'center',
          width: '20%',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      list: [],
      selectedRowKeys:[],
      ids:[],
      fileList:[]
    }
  },
  filters: {},
  created () {
    this.initColumnsSetting('purchaseDetail')
  },
  computed: {},
  watch: {},
  mounted () {},
  methods: {
    onClose () {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
      this.$emit('close')
    },
    // 表单重置
    reset () {
      this.form = {
        id: undefined,

        purchaseCode: undefined,

        supplierCode: undefined,

        warehouseId: undefined,

        deptId: undefined,

        purchaseDate: undefined,

        sendDate: undefined,

        remark: undefined,

        detailList: undefined,

        payList: undefined

      }
    },
    formatterTime(val){
      return val ? moment(val).format('YYYY-MM-DD') : ''
    },
    /** 新增按钮操作 */
    handleAdd (row) {
      this.reset()
      this.open = true
      this.formTitle = row.id ? '修改采购单' : '新增采购单';
      this.form = row
      if(this.form.detailList && this.form.detailList.length){
        this.dataSource = JSON.parse(JSON.stringify(this.form.detailList))
      }
      if(this.form.id) {
        this.form.deptObj = { ids: row.deptId, names: row.deptName }
      }else{
        this.$set(this.form,'purchaseDate',moment(new Date()).format('YYYY-MM-DD'))
      }
      this.selectWarehouse();
    },
    handleView(row) {
      this.reset()
      this.open = true
      this.formTitle = '查看采购单';
      this.form = row
      this.loading = true
      if(row.id) {
        this.form.deptObj = { ids: row.deptId, names: row.deptName }
        if(row.status==2){
          this.disabled = true
        }else{
          this.disabled = false
        }
      }
      let arr =  JSON.parse(JSON.stringify(this.form.detailList))
      this.dataSource = arr.map(v=>{
        v.unitList = []
        v.unit = +v.unit
        if(v.bizProduct){
          v.productCode = v.bizProduct.productCode
          v.model = v.bizProduct.model
          v.color = v.bizProduct.color
          v.brand = v.bizProduct.brand
          v.spec = v.bizProduct.spec
          v.unitList.push({key:1,name:v.bizProduct.unit},{key:2,name:v.bizProduct.assistUnitA},{key:3,name:v.bizProduct.assistUnitB})
        }
        return v
      })
      this.selectWarehouse();
      
      this.countTotal()
    },
    changeAmount(row,index){
      if(row.totalAmount && row.productNumber){
        row.unitPrice = row.totalAmount / row.productNumber
      }
      this.dataSource.splice(index,1,row)

    },
    handleDelDetail(row){
      let that = this
      const productIds = row.id || this.ids
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk() {
          let selectedList = JSON.parse(JSON.stringify(that.dataSource));
          selectedList.forEach((item, index) => {
            if (row.id) {
              that.dataSource = that.dataSource.filter(item => item.id != row.id)
              return;
            } else {
              that.selectedRows.forEach(item2 => {
                that.dataSource = that.dataSource.filter(item => item.id != item2.id)
                return;
              })
            }
          })
          that.$message.success(
            '删除成功',
            3
          )
          that.onSelectChange([], [])
          return;
        },
        onCancel() { }
      })
    },
    
    handleDelDetail(row,index){
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk:()=>{
          this.dataSource.splice(index,1)
        }
      })
    },
    /** 付款按钮操作 */
    handlePay (row) {
      this.reset()
      this.open = true
      this.formTitle = '采购单付款';
      this.form = row
    },
    savePay(row){
      this.$refs.form.validate(valid => {
        if (valid) {
          row.payType = 1
          const saveForm = JSON.parse(JSON.stringify(row))
          if (row.id !== undefined) {
            updateBizPayable(saveForm).then(response => {
              this.$message.success('更新成功', 3)
              this.open = false
              this.$emit('ok')
            })
          } else {
            addBizPayable(saveForm).then(response => {
              this.$message.success('新增成功', 3)
              this.open = false
              this.$emit('ok')
            })
          }
        } else {
          this.disabled = false
          return false
        }
      })
    },
    changeDate(row){
      row.payDate = this.formatterTime(row.payDate)
    },
    handleAddPay(){
      this.form.payList.push({purchaseCode:this.form.purchaseCode,supplierCode:this.form.supplierCode,payAccount:undefined,payAmount:'',payDate:'',remark:'',flag:false})
    },
    handleUpdate(row){
      row.flag = false
    },
    /** 提交按钮 */
    submitForm: function (closeDialog) {
      this.closeDialog = closeDialog
      this.disabled = true
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log(this.form.deptId,'this.form.deptId')
          const saveForm = JSON.parse(JSON.stringify(this.form))
          if (this.form.deptObj !== undefined) {
            saveForm.deptId = this.form.deptObj.ids
          }
          if(!this.dataSource || this.dataSource.length==0) {
            this.$message.error('请选择采购商品', 3)
            this.disabled = false
            return false;
          }
          // let flag = true;
          // this.dataSource.forEach(item=>{
          //   if(item.totalAmount<=0) {
          //     this.$message.error('采购金额必须大于0', 3)
          //     this.disabled = false
          //     flag = false;
          //     return;
          //   }
          // })
          // if(!flag) {
          //   this.disabled = false
          //   return false;
          // }
          saveForm.detailList = this.dataSource.filter(v => v[this.columns[0].dataIndex] !== '合计');
          if (this.form.id !== undefined) {
            updateBizPurchase(saveForm).then(res => {
              console.log('res :>> ', res);
              if(res.code == 200){
                this.$message.success('更新成功', 3)
                this.open = false
                this.$emit('ok')
                this.$emit('close')
                this.disabled = false
              }else{
                this.disabled = false
                this.$message.error(res.msg)
              }
            }).catch(e=>{
              this.disabled = false
            })
          } else {
            addBizPurchase(saveForm).then(res => {
              this.$message.success('新增成功', 3)
                this.$emit('ok')
                this.open = false
                this.$emit('ok')
                this.$emit('close')
                this.disabled = false
            }).catch(e=>{
              this.disabled = false
            })
          }
        } else {
          this.disabled = false
          return false
        }
      })
    },
    back () {
      const index = '/biz/bizpurchase/index'
      this.$router.push(index)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.id)
      this.single = selectedRowKeys.length == 1
      this.multiple = selectedRowKeys.length
    },
    
    handleDeleteRows() {
      if (!this.selectedRowKeys.length) {
        this.$message.error(
          '请选择要删除的数据',
          3
        )
        return
      }
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk: () => {
          this.dataSource = this.dataSource.filter((v, index) => !this.selectedRowKeys.includes(index) && !this.selectedRowKeys.includes(v.id))
          this.selectedRowKeys = []
          this.multiple = false
          this.$message.success(
            '删除成功',
            3
          )
        }
      })
    },
    modify() {
      this.disabled = false
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk() {
          return delBizPurchase(row.id)
            .then(() => {
              that.$message.success('删除成功', 3)
              that.open = false
              that.$emit('ok')
            })
        },
        onCancel() { }
      })
    },
    /** 删除按钮操作 */
    handlePayDelete(row) {
      if(row.id) {
        var that = this
        this.$confirm({
          title: '确认删除所选中数据?',
          onOk() {
            return delBizPayable(row.id)
              .then(() => {
                that.$message.success(
                  '删除成功',
                  3
                )
                that.form.payList.splice(row,1)
              })
          },
          onCancel() { }
        })
      }else{
        this.form.payList.splice(row,1)
      }

    },
    audit(row,status){
      let that = this
      let title='确认审核所选中数据?';
      if(status==1) {
        title='确认反审所选中数据?';
      }
      that.$confirm({
        title: title,
        onOk () {
          return auditPurchase(row.id,status)
            .then((res) => {
              that.$message.success('更新成功', 3)
              that.open = false
              that.$emit('ok')
          })
        },
        onCancel () {}
      })
    },
    handleSubDelete(row) {
      console.log('row :>> ', row);
      var that = this
      const productIds = row.id || this.ids
      this.$confirm({
        title: '确认删除所选中数据?',
        onOk () {
          let selectedList = JSON.parse(JSON.stringify(that.list));
          selectedList.forEach((item,index)=>{
            if(row.id) {
              that.list= that.list.filter(item => item.id!=row.id)
              return;
            } else {
              that.selectedRows.forEach(item2=>{
                that.list= that.list.filter(item => item.id!=item2.id)
                return;
              })
            }
          })
          that.$message.success(
            '删除成功',
            3
          )
          that.onSelectChange([], [])
          return;
        },
        onCancel () {}
      })
    },
    handleAddProduct() {
      this.showProductModal = true
      this.$nextTick(() => {
        this.$refs.bizProduct.handleAddProduct([]);
      })
    },
    selectWarehouse(bol = false) {
      if(!this.form.warehouseId) {
        return;
      }
      if (bol) {
        // 清空表体所有仓位
      this.dataSource.forEach(val=>{
        this.$set(val,'spaceId','')
      })
      }
      listBizWarehouseSpaceByWarehouseId(this.form.warehouseId).then(res=>{
        this.spaceList=res.data;
        this.loading = false
        // if(this.spaceList && this.spaceList.length>0) {
        //   this.dataSource.forEach(item=>{
        //     item.spaceId=this.spaceList[0].id;
        //   });
        // }
      });
    },
    selectProduct(selectedRows) {
      selectedRows.forEach(item=>{
        let arr = [{key:1,name:item.unit},{key:2,name:item.assistUnitA},{key:3,name:item.assistUnitB}]
        item.unitList.push(...arr.filter(v=>v.name))
        item.productNumber = item.productNumber?item.productNumber:0;
        item.tempSalePrice = item.salePrice;
        if (item.defaultWarehousingUnit == 2) {
          item.unit = 2
          item.unitPrice = item.salePriceA
        } else if (item.defaultWarehousingUnit == 3) {
          item.unit = 3
          item.unitPrice = item.salePriceB
        } else {
          item.unit = 1;
          item.unitPrice=item.salePrice;
        }
        item.totalAmount = 0.00;
        item.productId = item.id
        delete item.id
        this.$forceUpdate();
      })
      
      // 合计位置
      if (this.dataSource.length && this.dataSource[this.dataSource.length - 1][this.columns[0].dataIndex] === '合计') {
        this.dataSource.splice(this.dataSource.length - 1,0,...JSON.parse(JSON.stringify(selectedRows)))
      }else{
        this.dataSource.push(...JSON.parse(JSON.stringify(selectedRows)))
      }
      this.countTotal()
    },
    handleChange(info) {
      if (info.file.status == 'done') {
       this.fileList=info.fileList;
      }
    },
    handleRemove(info) {
      this.fileList=this.fileList.filter(function(item) {
        return item.uid != info.uid
      })
    },

    changeUnit(record) {
      if (record.unit == 1) {
        record.unitPrice = +record.purchasesPrice || (record.bizProduct && +record.bizProduct.purchasesPrice) || 0
      } else if (record.unit == 2) {
        record.unitPrice = +record.purchasesPriceA || (record.bizProduct && +record.bizProduct.purchasesPriceA) || 0
      } else if (record.unit == 3) {
        record.unitPrice = +record.purchasesPriceB || (record.bizProduct && +record.bizProduct.purchasesPriceB) || 0
      }
      record.totalAmount = record.unitPrice * record.productNumber;
      this.$forceUpdate();
      this.countTotal()
    },
    changeUnitPrice(record) {
      record.totalAmount = record.unitPrice * record.productNumber;
      console.log(record.totalAmount)
      this.$forceUpdate();
      this.countTotal()
    },
    
    /**
     * 设置table的row的class
     * @param {obj} row 
     * @param {number} index 
     */
     getRowClassName(row,index,type){
      let arr = this[type].filter(v=>v.productCode === row.productCode)
      if (arr.length > 1) {
        return 'multiple_table_row'
      }
    },
    getCheckboxProps(record){
      // 禁用合计以及已审核状态下参与库存计算的产品
      let flag = record[this.columns[0].dataIndex] === '合计'
      return { props: { disabled: flag } }
    },
    countTotal() {
      const getTotal = (dataSource, key) => {
        return dataSource.reduce((pre, cur) => {
          return this.$toDecimal(pre + +cur[key])
        }, 0)
      }
      // // 合计
      // 1.产品明细
      if (this.dataSource.length) {
        if (this.dataSource[this.dataSource.length - 1][this.columns[0].dataIndex] === '合计') {
          this.dataSource.splice(this.dataSource.length - 1, 1)
          let item = {
            productNumber: getTotal(this.dataSource, 'productNumber'),
            // unitPrice: getTotal(this.dataSource, 'unitPrice'),
            totalAmount: getTotal(this.dataSource, 'totalAmount'),
            disabled: true,
            [this.columns[0].dataIndex]: '合计'
          }
          this.dataSource.push(item)
        } else {
          let item = {
            productNumber: getTotal(this.dataSource, 'productNumber'),
            // unitPrice: getTotal(this.dataSource, 'unitPrice'),
            totalAmount: getTotal(this.dataSource, 'totalAmount'),
            disabled: true,
            [this.columns[0].dataIndex]: '合计'
          }
          this.dataSource.push(item)
        }
      }
      console.log('this.dataSource :>> ', this.dataSource);
    }
  }
}
